<template>
  <div class="digital-human">
    <!-- 图片容器 -->
    <div class="image-container" ref="imageContainer">
      <!-- 在此容器中动态添加图片 -->
    </div>

    <!-- 音频控件 -->
    <audio ref="audioElement" controls></audio>

    <!-- 输入框和提交按钮 -->
    <div class="input-section">
      <input v-model="userInput" type="text" placeholder="请输入内容" class="input-box"/>
      <button @click="handleSubmit" class="submit-button" :disabled="isSubmitting">提交</button>
    </div>

    <div ref="linkSection" class="link-section" v-show="isLinkVisible">
      <div v-for="(url, index) in urls" :key="index">
        链接地址: <a :href="url" class="link">{{ url }}</a>
      </div>
    </div>
  </div>
</template>

<script>
import {onMounted, ref} from 'vue';
import axios from 'axios';

export default {
  setup() {
    const userInput = ref('');
    const audioElement = ref(null);
    const isSubmitting = ref(false);
    const errorMessage = ref('');
    const isLinkVisible = ref(false);
    const urls = ref([]);
    const frameIndex = ref(1);
    const totalFrames = 30;
    const framePathTemplate = "/compressionImage/1717658488515_3480_";
    const imageContainer = ref(null); // 引用 image-container 容器
    let frameInterval = null;

    const handleAudioEnded = () => {
      stopAnimation();
      imageIni();
    };

    const updateFrame = () => {
      if (frameIndex.value > totalFrames) {
        frameIndex.value = 1;
      }

      // 创建新的图片元素
      const frameNumber = String(frameIndex.value).padStart(6, '0');
      const imgElement = document.createElement('img');
      imgElement.src = `${framePathTemplate}${frameNumber}.png`;
      imgElement.classList.add('frame-image');

      // 清空并更新图片容器
      if (imageContainer.value && imageContainer.value.firstChild) {
        imageContainer.value.removeChild(imageContainer.value.firstChild);
      }
      imageContainer.value.appendChild(imgElement);

      frameIndex.value++;
    };

    const startAnimation = () => {
      if (!frameInterval) {
        frameInterval = setInterval(updateFrame, 100);
      }
    };

    const stopAnimation = () => {
      if (frameInterval) {
        clearInterval(frameInterval);
        frameInterval = null;
      }
    };

    const handleSubmit = async () => {
      if (userInput.value) {
        try {
          isSubmitting.value = true;
          errorMessage.value = '';

          await testToAudio(userInput.value);
        } catch (error) {
          console.error('请求出错:', error);
          errorMessage.value = '请求失败，请稍后重试。';
        } finally {
          userInput.value = '';
          isSubmitting.value = false;
        }
      }
    };

    const testToAudio = async (message) => {
      const audioResponse = await axios.post('https://test-wd-api.iwanshang.cloud/kma/gpt/audio/text2Audio', {
        text: message
      });

      if (audioResponse.data.code === 200 && audioResponse.data.audio) {
        const base64Audio = audioResponse.data.audio;

        audioElement.value.src = `data:audio/wav;base64,${base64Audio}`;
        audioElement.value.play();
        startAnimation();
      } else {
        console.error('未能获取到有效的音频数据');
      }
    };

    onMounted(() => {
      if (audioElement.value) {
        audioElement.value.addEventListener('ended', handleAudioEnded);
      }
      imageIni();
    });

    const imageIni = () => {
      frameIndex.value = 1;
      updateFrame();
    };

    return {
      userInput,
      isSubmitting,
      errorMessage,
      isLinkVisible,
      urls,
      handleSubmit,
      audioElement,
      imageIni,
      imageContainer
    };
  },
};
</script>

<style scoped>
audio {
  display: none;
}

.digital-human {
  position: relative;
  width: 90vw;
  max-width: 360px;
  height: 60vh;
  max-height: 640px;
  background: transparent;
  transition: transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out;
}

.image-container {
  background-color: transparent; /* 可选 */
}

.frame-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.input-box {
  padding: 10px;
  margin-bottom: 10px;
  width: 100%;
  max-width: 300px;
  border-radius: 5px;
  border: 1px solid #ccc;
}

.submit-button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.submit-button:hover {
  background-color: #0056b3;
}

.link-section {
  margin-top: 20px;
}

.link {
  color: #3498db;
  font-size: 1.2rem;
  text-decoration: none;
  font-weight: bold;
}

.link:hover {
  color: #2980b9;
  text-decoration: underline;
}
</style>
